<?php
class db{
	protected $db 			=	'';		//数据库
	protected $table_name	=	'';
	protected $conf  		=	'';
	protected $where		=	'';
    protected $field 		=	'*';
    protected $order 		=	'';
    protected $limit 		=	'';
    protected $join 		=	'';
    protected $selectSql  	= 	'SELECT %FIELD% FROM %TABLE% %JOIN% %WHERE% %ORDER% %LIMIT%';
    public $lastSql		=	'';
    
	function __construct($name){
		$this->init($name);
		return $this->db;
	}

	function init($name){
		$this->table_name=$name;
		$this->conf 	 =include_once(SYS_PATH.'config.php');
		$this->connect();
	}

	private function connect(){
		$conf=$this->conf;
		$con = mysql_connect($conf['DB_HOST'].':'.$conf['DB_PORT'],$conf['DB_USER'],$conf['DB_PWD']);
		if(!$con){
			die('Could not connect: ' . mysql_error());
		}
		mysql_select_db($conf['DB_NAME'],$con) or die('database select error:'.mysql_error());  

		$this->db=$con;
	}

	public function field($field){
		if(is_string($field) && strpos($field,',')) {
            $this->field=$field;
        }
        return $this;
	}

	public function join($join){
		$this->join=is_string($join)?$join:'';
		return $this;
	}

	public function order($order){
		$this->order=is_string($order)?'order by '.$order:'';
		return $this;
	}

	public function limit($m=0,$n=0){	//第一个参数为偏移量，第二个参数为数量
		$this->limit=($n>0)?'limit '.intval($m).','.intval($n):'limit '.intval($m);
		return $this;
	}

	public function find(){
		$this->limit(1);
		$this->select();
	}

	public function select(){
		$sql=str_replace(
			array('%FIELD%','%TABLE%','%JOIN%','%WHERE%','%ORDER%','%LIMIT%'), 
			array($this->field,$this->table_name,$this->join,$this->where,$this->order,$this->limit), 
			$this->selectSql
		);
		$this->lastSql=$sql;
		$res_id=mysql_query($sql);
		while($re=mysql_fetch_assoc($res_id)){
			$result[]=$re;
		}

		return empty($result)?'':$result;
	}

	public function where($data='',$parse=null){
		/*数据过滤，统一用mysql_real_escape_string来过滤*/
		if(!is_null($parse) && is_string($data)){	//如果是字符串的话
			if(!is_array($parse)){  
				$parse = func_get_args();
				array_shift($parse);
			}

			array_walk_recursive($parse, array(&$this,'escapeString'));
			$data = vsprintf($data,$parse);
		}
		if(is_array($data)){
			array_walk_recursive($data, array(&$this,'escapeString'));
			print_r($data);
		}

		/*字符串拼接处理*/
		if(is_array($data)){
			$str='';
			foreach ($data as $key => $value){
				if(preg_match('/^[A-Z_\-.a-z0-9]+$/',trim($key))){	//支持的字段格式：字母，数字，-_.
					$str.=$key."=".$value." and";
				}
				else{
					unset($data[$key]);
				}
			}
			$str=substr($str,0,-3);		//去掉尾部多余的and
			$this->where=empty($str)?'':'where '.$str;
		}
		else{
			$this->where=empty($data)?'':'where '.$data;
		}
		
	    return $this;
	}

	private function escapeString(& $value,$key){
		if(is_string($value)){
			$value='\''.mysql_real_escape_string($value).'\'';
		}
	}
}

?>